"""
智能旅游助手Agent使用示例
演示如何使用LangGraph Agent进行旅游咨询和路线规划
"""

import os
import sys
import logging
from typing import List, Dict, Any

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from agent.travel_agent import TravelAgent
from agent.workflow_visualizer import WorkflowVisualizer

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class TravelAgentDemo:
    """旅游助手演示类"""
    
    def __init__(self):
        """初始化演示"""
        try:
            self.agent = TravelAgent()
            logger.info("旅游助手Agent初始化成功")
        except Exception as e:
            logger.error(f"初始化Agent失败: {str(e)}")
            raise
    
    def run_demo_scenarios(self):
        """运行演示场景"""
        print("=" * 60)
        print("智能旅游助手 Agent 演示")
        print("=" * 60)
        
        # 场景1：旅游攻略查询
        self._demo_travel_guide_scenario()
        
        # 场景2：路线规划查询
        self._demo_route_planning_scenario()
        
        # 场景3：需要澄清的路线规划
        self._demo_clarification_scenario()
        
        # 场景4：多用户会话隔离
        self._demo_multi_user_scenario()
        
        print("\n" + "=" * 60)
        print("演示完成！")
        print("=" * 60)
    
    def _demo_travel_guide_scenario(self):
        """演示旅游攻略查询场景"""
        print("\n📍 场景1：旅游攻略查询")
        print("-" * 40)
        
        user_id = "user_001"
        questions = [
            "请推荐一个位于成都，历史韵味比较浓厚的景点",
            "成都的美食有哪些特色？",
            "成都的交通情况怎么样？"
        ]
        
        for i, question in enumerate(questions, 1):
            print(f"\n问题 {i}: {question}")
            response = self.agent.chat(user_id, question)
            print(f"回答: {response}")
            print("-" * 40)
    
    def _demo_route_planning_scenario(self):
        """演示路线规划场景"""
        print("\n🗺️ 场景2：路线规划查询")
        print("-" * 40)
        
        user_id = "user_002"
        questions = [
            "我从成都宽窄巷子到武侯祠怎么去比较方便？",
            "从春熙路到熊猫基地，我想骑车过去",
            "从双流机场到市中心，坐地铁怎么走？"
        ]
        
        for i, question in enumerate(questions, 1):
            print(f"\n问题 {i}: {question}")
            response = self.agent.chat(user_id, question)
            print(f"回答: {response}")
            print("-" * 40)
    
    def _demo_clarification_scenario(self):
        """演示需要澄清的场景"""
        print("\n❓ 场景3：需要澄清的路线规划")
        print("-" * 40)
        
        user_id = "user_003"
        
        # 第一次询问（信息不完整）
        print("\n问题: 怎么去武侯祠？")
        response1 = self.agent.chat(user_id, "怎么去武侯祠？")
        print(f"回答: {response1}")
        
        # 提供澄清信息
        print("\n澄清: 我从成都宽窄巷子过去")
        response2 = self.agent.chat(user_id, "我从成都宽窄巷子过去")
        print(f"回答: {response2}")
        
        print("-" * 40)
    
    def _demo_multi_user_scenario(self):
        """演示多用户会话隔离"""
        print("\n👥 场景4：多用户会话隔离")
        print("-" * 40)
        
        # 用户1的对话
        user1_id = "user_001"
        print(f"\n用户 {user1_id} 的对话:")
        response1 = self.agent.chat(user1_id, "推荐一个成都的景点")
        print(f"回答: {response1}")
        
        # 用户2的对话
        user2_id = "user_002"
        print(f"\n用户 {user2_id} 的对话:")
        response2 = self.agent.chat(user2_id, "从春熙路到熊猫基地怎么走？")
        print(f"回答: {response2}")
        
        # 显示会话历史
        print(f"\n用户 {user1_id} 的会话历史:")
        history1 = self.agent.get_session_history(user1_id)
        for msg in history1[-2:]:  # 只显示最后2条
            print(f"  {msg['type']}: {msg['content']}")
        
        print(f"\n用户 {user2_id} 的会话历史:")
        history2 = self.agent.get_session_history(user2_id)
        for msg in history2[-2:]:  # 只显示最后2条
            print(f"  {msg['type']}: {msg['content']}")
        
        print("-" * 40)
    
    def interactive_chat(self):
        """交互式聊天"""
        print("\n" + "=" * 60)
        print("交互式聊天模式")
        print("输入 'quit' 退出，输入 'clear' 清除会话历史")
        print("=" * 60)
        
        user_id = input("请输入您的用户ID: ").strip()
        if not user_id:
            user_id = "default_user"
        
        print(f"\n欢迎，{user_id}！我是您的智能旅游助手。")
        print("我可以帮您：")
        print("1. 推荐旅游景点、美食、交通等信息")
        print("2. 规划出行路线")
        print("3. 回答各种旅游相关问题")
        
        while True:
            try:
                user_input = input(f"\n{user_id}> ").strip()
                
                if user_input.lower() == 'quit':
                    print("再见！")
                    break
                elif user_input.lower() == 'clear':
                    self.agent.clear_session(user_id)
                    print("会话历史已清除")
                    continue
                elif not user_input:
                    continue
                
                # 处理用户输入
                response = self.agent.chat(user_id, user_input)
                print(f"助手> {response}")
                
            except KeyboardInterrupt:
                print("\n\n再见！")
                break
            except Exception as e:
                print(f"处理您的请求时出现错误: {str(e)}")
    
    def generate_workflow_diagram(self):
        """生成工作流图"""
        print("\n正在生成工作流图...")
        try:
            visualizer = WorkflowVisualizer()
            output_path = "/Users/pengxiong/workspace/pyWorkspace/traval-agent/travel_agent_workflow.png"
            visualizer.create_workflow_diagram(output_path)
            print(f"工作流图已生成: {output_path}")
        except Exception as e:
            print(f"生成工作流图失败: {str(e)}")

def main():
    """主函数"""
    try:
        demo = TravelAgentDemo()
        
        # 生成工作流图
        demo.generate_workflow_diagram()
        
        # 运行演示场景
        demo.run_demo_scenarios()
        
        # 询问是否进入交互模式
        while True:
            choice = input("\n是否进入交互式聊天模式？(y/n): ").strip().lower()
            if choice in ['y', 'yes', '是']:
                demo.interactive_chat()
                break
            elif choice in ['n', 'no', '否']:
                break
            else:
                print("请输入 y 或 n")
        
    except Exception as e:
        logger.error(f"运行演示时出错: {str(e)}")
        print(f"运行演示时出错: {str(e)}")

if __name__ == "__main__":
    main()
